<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-09-07 09:05:44
 * @Description: 租户基础信息管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-09-17 15:36:28
 * @FilePath: /qingshanERP/app/Http/Controllers/Console/Tenant/TenantController.php
 */

namespace App\Http\Controllers\Console\Tenant;

use Validator;
use App\Customize\Func;
use Illuminate\Http\Request;
use App\Models\Tenant\Tenant;
use App\Models\Tenant\TenantLevel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\QingShanERP\Supplier;
use App\Models\Tenant\SupplierTenant;
use App\Models\Tenant\SupplierContactTenant;

class TenantController extends Controller
{
    public function getList(Request $req)
    {
        try {
            $page = $req->input('page', 0);
            $size = $req->input('size', 10);
            $level_id = $req->input('level_id', '');
            $status = $req->input('status', '');
            $key = $req->input('key', '');
            $list = Tenant::with('tenant_level')->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('tenant_name', 'like', '%' . $key . '%');
                }
            })->where(function ($q) use ($level_id) {
                if ($level_id != '') {
                    $q->where('tenant_level_id', $level_id);
                }
            })->where(function ($q) use ($status) {
                if ($status != '') {
                    $q->where('status', $status);
                }
            })->where('del_flag', 0)->offset(($page - 1) * $size)->limit($size)->orderBy('id', 'desc')->get();
            $count = Tenant::where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('tenant_name', 'like', '%' . $key . '%');
                }
            })->where(function ($q) use ($level_id) {
                if ($level_id != '') {
                    $q->where('tenant_level_id', $level_id);
                }
            })->where(function ($q) use ($status) {
                if ($status != '') {
                    $q->where('status', $status);
                }
            })->where('del_flag', 0)->count();
            $res = ['list' => $list, 'total' => $count];
            return $this->resData(200, '获取数据成功...', $res);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请稍后再试...');
        }
    }

    public function postCreate(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'level_id' => 'required|integer',
                'phone' => 'required|regex:/^1[3456789]\d{9}$/',
                'tenant_name' => 'required|max:150',
                'email' => 'required|email',
                'password' => 'confirmed|min:6|max:15|alpha_dash',
            ]);
            $attrs = array(
                'level_id' => '级别ID',
                'phone' => '手机号',
                'tenant_name' => '租户名称',
                'email' => '邮箱',
                'password' => '密码'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $crypt = Func::str_random(10);
            $pwd = Func::makepwd($all['password'], $crypt);
            // 根据级别查到期时间
            $days = TenantLevel::where('id',$all['level_id'])->value('days');
            $last_date = date('Y-m-d H:i:s',time() + $days*24*3600);
            $create = ['tenant_level_id' => $all['level_id'], 'phone' => $all['phone'], 'tenant_name' => $all['tenant_name'], 'email' => $all['email'], 'password' =>$pwd, 'crypt' => $crypt,'last_date'=>$last_date,'lastip' =>'0.0.0.0','lasttime'=>date('Y-m-d H:i:s'), 'status' => 1];
            Tenant::create($create);
            return $this->resData(200, '添加成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '添加失败，请重新操作...',$e->getMessage().' - '.$e->getLine());
        }
    }
    //详情
    public function postDetail(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'tenant_id' => 'required',
            ]);
            $attrs = array(
                'tenant_id' => '租户ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('tenant_id');
            $info = Tenant::find($id);
            return $this->resData(200, '获取数据成功...', $info);
        } catch (\Throwable $e) {
            return $this->resData(500, '获取数据失败，请重新操作...');
        }
    }
    //编辑
    public function postEdit(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'tenant_id' => 'required',
                'level_id' => 'required|integer',
                'phone' => 'required|regex:/^1[3456789]\d{9}$/',
                'tenant_name' => 'required|max:150',
                'email' => 'required|email',
                'password' => 'nullable|confirmed|min:6|max:15|alpha_dash',
            ]);
            $attrs = array(
                'tenant_id' => '租户ID',
                'level_id' => '级别ID',
                'phone' => '手机号',
                'tenant_name' => '租户名称',
                'email' => '邮箱',
                'password' => '密码',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('tenant_id');
            $all = $request->all();
            // 根据级别查到期时间
            $days = TenantLevel::where('id', $all['level_id'])->value('days');
            $info = Tenant::find($id);
            $last_date = $info->last_date;
            if ($info->tenant_level_id != $all['level_id']) {
                // 当前剩余天数 + 新级别天数
                $last_date = date('Y-m-d H:i:s', strtotime($info->last_date) + $days * 24 * 3600);
            }
            $update = ['tenant_level_id' => $all['level_id'], 'phone' => $all['phone'], 'tenant_name' => $all['tenant_name'], 'email' => $all['email'], 'last_date' => $last_date,'status'=> $all['status'] == 'true' ? 1 : 0];
            if (!is_null($all['password'])) {
                $crypt = Func::str_random(10);
                $pwd = Func::makepwd($all['password'], $crypt);
                $update['crypt'] = $crypt;
                $update['password'] = $pwd;
            }
            Tenant::where('id', $id)->update($update);
            return $this->resData(200, '编辑成功...');
        } catch (\Throwable $e) {
            return $this->resData(500, '编辑失败，请重新操作...',$e->getLine().' - '.$e->getMessage());
        }
    }

    //删除
    public function postRemove(Request $request)
    {
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->input(), [
                'tenant_id' => 'required|array',
            ]);
            $attrs = array(
                'tenant_id' => '租户ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                DB::rollBack();
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $id = $request->input('tenant_id');
            Tenant::whereIn('id', $id)->update(['del_flag' => 1]);
            SupplierTenant::whereIn('tenant_id',$id)->delete();
            SupplierContactTenant::whereIn('tenant_id', $id)->delete();
            DB::commit();
            return $this->resData(200, '删除成功...');
        } catch (\Throwable $e) {
            DB::rollBack();
            return $this->resData(500, '删除失败，请重新操作...');
        }
    }
    // 关联供应商
    public function getSupplier(Request $request){
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->input(), [
                'tenant_id' => 'required|integer',
            ]);
            $attrs = array(
                'tenant_id' => '租户ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                DB::rollBack();
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $list = Supplier::where('status', 1)->where('del_flag', 0)->orderBy('id', 'desc')->get();
            $ids = SupplierTenant::where('tenant_id', $all['tenant_id'])->pluck('supplier_id');
            DB::commit();
            return $this->resData(200, '关联成功...',['list' => $list,'ids' =>$ids]);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->resData(500, '删除失败，请重新操作...');
        }
    }
    public function postSupplier(Request $request){
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->input(), [
                'tenant_id' => 'required|integer',
                'supplier_id' => 'required|array',
            ]);
            $attrs = array(
                'tenant_id' => '租户ID',
                'supplier_id' => '供应商',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                DB::rollBack();
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            SupplierTenant::where('tenant_id',$all['tenant_id'])->delete();
            $insert = [];
            foreach ($all['supplier_id'] as $s) {
                $insert[] = ['supplier_id' => $s, 'tenant_id' => $all['tenant_id']];
            }
            SupplierTenant::insert($insert);
            DB::commit();
            return $this->resData(200, '关联成功...');
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->resData(500, '删除失败，请重新操作...');
        }
    }
}
